/*
 * <h3>Title:wheel-parent系统</h3>
 * <p>Copyright (c) 2020, wnfbx@163.com. All rights reserved.</p>
 * @author wnfbx@163.com
 */
package com.wheel.autoconfigure.dynamicdatasource.processor;

import com.wheel.autoconfigure.dynamicdatasource.annotation.DynamicDataSourceKey;
import com.wheel.autoconfigure.dynamicdatasource.datasource.DynamicDataSourceKeyType;
import com.wheel.autoconfigure.dynamicdatasource.datasource.DynamicRoutingDataSource;

/**
 * <dt>Description:NoJTADynamicDataSourceDetermineProcessor</dt>
 * <dd>当没有jta分布试事务时，主数据源一旦选择不能切换</dd>
 *
 * @author wnfbx@163.com
 * @version 1.0 <i>2020/1/9 16:01</i>
 * @since jdk1.7+
 */
public class NoJTADynamicDataSourceDetermineProcessor extends AbstractDynamicDataSourceDetermineProcessor implements DynamicDataSourceDetermineProcessor {

    @Override
    public String process(DynamicDataSourceKey dynamicDataSourceKey) {
        String determine = DynamicRoutingDataSource.getLast();
        // 如果是首次进入或者之前是从数据源
        if (determine == null || slaveKeys.contains(determine)) {
            return determineByDynamicDataSourceKey(dynamicDataSourceKey);
        }
        // 如果是主数据源
        else {
            if (isJTA) {
                String name = dynamicDataSourceKey.name();
                if (!"".equals(name)) {
                    //先判断当前的数据源名是master还是slave
                    if (masterKeys.contains(name)) {
                        return name;
                    } else {
                        return determine;
                    }
                }
                // 如果没固定使用数据源，因为之前是主，之后默认都选主
                return masterBalancer.determine(masterKeys);
            } else {
                // 直接返回
                // 假设在方法递归的时候，父级方法的主数据源已经保存成功，不能因为接下来的查询所使用从数据源出现异常，就把事务回滚，这个显然是不合理的
                return determine;
            }
        }
    }

    private String determineByDynamicDataSourceKey(DynamicDataSourceKey dynamicDataSourceKey) {
        // 名称指定模式
        String name = dynamicDataSourceKey.name();
        if (!"".equals(name)) {
            return name;
        }
        //负载均衡模式
        String masterSlave = dynamicDataSourceKey.masterSlave();
        if (DynamicDataSourceKeyType.MasterSlave.MASTER.getCode().equals(masterSlave)) {
            return masterBalancer.determine(masterKeys);
        } else {
            return slaveBalancer.determine(slaveKeys);
        }
    }

}
